<script lang="ts" setup>
import PostApi, { PostEditRequest } from "@/api/post";
import { handleTree } from "@/utils/tree";
import CategoryApi from "@/api/category";
import { message } from "@/utils/message";
import MarkdownEditor from "@/components/markdown-editor/index.vue";
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  FormInstance,
  FormRules
} from "element-plus";
import { onMounted } from "vue";
import { ref, Ref, reactive } from "vue";
import { useRoute } from "vue-router";

export interface Props {
  modelValue: boolean;
  readonly id: number | null;
}
const route = useRoute();
const treeData = ref([]);
const defaultPostInfo: PostEditRequest = {
  id: 0,
  title: "",
  slug: "",
  summary: "",
  content: "",
  categoryId: 0
};

const postInfo: Ref<PostEditRequest> = ref(defaultPostInfo);
onMounted(async () => {
  const postId = route.query?.id as string;
  if (postId != null) {
    getPostInfo(parseInt(postId));
  }
  await loadTree();
});
async function getPostInfo(id: number) {
  if (route.query.id) {
    const postDetail = await PostApi.getInfo(id);
    postInfo.value = { ...postDetail };
  } else {
    postInfo.value = { ...defaultPostInfo };
  }
}
const loading = ref(true);
async function loadTree() {
  loading.value = true;
  const data = await CategoryApi.list({ keyword: null });
  treeData.value = handleTree(data);
  setTimeout(() => {
    loading.value = false;
  }, 100);
}

const formRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  title: [{ required: true, message: "请输入标题" }]
});
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (valid) {
      await PostApi.edit({
        ...postInfo.value
      });
      message("修改成功", { type: "success" });
    } else {
      return false;
    }
  });
};
</script>
<template>
  <el-form
    ref="formRef"
    :model="postInfo"
    label-width="100px"
    class="demo-ruleForm"
    :rules="rules"
  >
    <el-form-item label="标题" prop="title">
      <el-input v-model="postInfo.title" type="text" />
    </el-form-item>
    <el-form-item label="链接" prop="slug">
      <el-input v-model="postInfo.slug" type="text" />
    </el-form-item>
    <el-form-item label="介绍" prop="summary">
      <el-input type="textarea" v-model="postInfo.summary" row="3" />
    </el-form-item>
    <el-form-item label="分类">
      <el-tree-select
        :data="treeData"
        v-model="postInfo.categoryId"
        default-expand-all
        check-strictly
        :props="{
          value: 'id',
          label: 'name',
          emitPath: false
        }"
        clearable
      />
    </el-form-item>
    <el-form-item label="内容" prop="content">
      <markdown-editor v-model="postInfo.content" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(formRef)">提交</el-button>
    </el-form-item>
  </el-form>
</template>
